﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Quartz;
using Common.Logging;
using OpenPop.Pop3;
using OpenPop.Mime;
using System.Data.SqlClient;
using System.Data;
using System.IO;
using OpenPop.Pop3.Exceptions;

namespace EmailSchedule
{
    public class GetEmailCustomerJob : IJob
    {

        private static ILog _log = LogManager.GetLogger(typeof(GetEmailCustomerJob));
        public virtual void Execute(IJobExecutionContext context)
        {
            Message message = null;
             string attachDirectory = "";
             _log.Info(string.Format("GetEmailCustomerJob! - {0}", System.DateTime.Now.ToString("r")));
            //System.IO.MemoryStream stream = new System.IO.MemoryStream();            
             try
             {
                 using (Pop3Client client = new Pop3Client())
                 {
                     // Connect to the server
                     client.Connect("pop.gmail.com", 995, true);

                     // Authenticate ourselves towards the server
                     client.Authenticate(Helper.emailServerAddress,Helper.emailServerPassword);

                     // Fetch all the current uids seen
                     List<string> uids = client.GetMessageUids();

                     if (uids.Count > 0)
                     {
                         for (int i = 1; i <= uids.Count; i++)
                         {
                             try
                             {
                                 if (chec_Data(uids[i-1]))
                                 {
                                     Helper.uidList.Add(uids[i-1]);
                                     attachDirectory = "";
                                     message = client.GetMessage(i);
                                     StringBuilder builder = new StringBuilder();
                                     MessagePart plainText = message.FindFirstHtmlVersion();
                                     builder.Append(plainText.GetBodyAsText());

                                     List<MessagePart> attachments = message.FindAllAttachments();
                                     if (attachments.Count > 0)
                                     {
                                         attachDirectory = Helper.attachFilePath + "/" + message.Headers.MessageId;
                                         foreach (MessagePart attachmentMessagePart in attachments)
                                         {
                                             if (!Directory.Exists(attachDirectory))
                                             {
                                                 Directory.CreateDirectory(attachDirectory);
                                             }
                                             FileInfo fileAttach = new FileInfo(attachDirectory + "/" + attachmentMessagePart.FileName);
                                             attachmentMessagePart.Save(fileAttach);
                                         }
                                     }
                                     Helper.LogToFile(LogFileType.MESSAGE, "#" + message.Headers.MessageId.Trim() + "#" + message.Headers.Subject + "#" + builder.ToString() + "#" + message.Headers.DateSent.ToString("dd/MM/yyyy HH:mm:ss") +
                                         "#" + message.Headers.From.Address.Trim() + "#" + message.Headers.To[0].Address.Trim() + "#" + attachDirectory, Helper.getEmailCustomer);
                                     using (SqlConnection cn = new SqlConnection(Helper.sqlConnectString))
                                     {
                                         cn.Open();
                                         using (SqlCommand cm = cn.CreateCommand())
                                         {

                                             cm.CommandText = "ADD_EMAIL";
                                             cm.CommandType = CommandType.StoredProcedure;
                                             cm.Parameters.AddWithValue("@MessageId", message.Headers.MessageId.Trim());
                                             cm.Parameters.AddWithValue("@Subject", message.Headers.Subject);
                                             cm.Parameters.AddWithValue("@Content", builder.ToString());
                                             cm.Parameters.AddWithValue("@FromDate", message.Headers.DateSent.ToString("dd/MM/yyyy HH:mm:ss"));
                                             cm.Parameters.AddWithValue("@FromName", message.Headers.From.Address.Trim().Split('@')[0]);
                                             cm.Parameters.AddWithValue("@FromEmail", message.Headers.From.Address.Trim());
                                             cm.Parameters.AddWithValue("@ToEmail", message.Headers.To[0].Address.Trim());
                                             cm.Parameters.AddWithValue("@AttachFile", attachDirectory);
                                             cm.Parameters.AddWithValue("@Status", 'R');
                                             cm.ExecuteNonQuery();
                                         }
                                     } 
                                 }
                             }
                             catch (Exception ex)
                             {                             
                              Helper.LogToFile(LogFileType.EXCEPTION, "- GetEmailCustomerJob - "+ ex.Message,Helper.getEmailCustomer);
                             }
                         }
                         //     cn.Close();        
                     }
                 }
             }
             catch (InvalidLoginException)
             {
                 //MessageBox.Show(this, "The server did not accept the user credentials!", "POP3 Server Authentication");
             }
             catch (PopServerNotFoundException)
             {
                 //MessageBox.Show(this, "The server could not be found", "POP3 Retrieval");
             }
             catch (PopServerLockedException)
             {
                 //MessageBox.Show(this, "The mailbox is locked. It might be in use or under maintenance. Are you connected elsewhere?", "POP3 Account Locked");
             }
             catch (LoginDelayException)
             {
                 //MessageBox.Show(this, "Login not allowed. Server enforces delay between logins. Have you connected recently?", "POP3 Account Login Delay");
             }
             catch (Exception e)
             {
                 //MessageBox.Show(this, "Error occurred retrieving mail. " + e.Message, "POP3 Retrieval");
             }
             finally
             {

             }
           
        }
        public bool chec_Data(string uid)
        {
            try
            {
                if (Helper.uidList == null || Helper.uidList.Count == 0)
                {
                    return true;
                }
                else
                {
                    for (int i = 0; i < Helper.uidList.Count; i++)
                    {
                        if (uid == Helper.uidList[i])
                        {
                            return false;
                        }
                    }
                }
                return true;
            }
            catch
            {
                return true;
            }
        }
    }
}
